<template>
  <div>
    <button @click="toggleBox">移动盒子</button>
    <div class="box" :class="{ slideRight: isMoved, slideLeft: !isMoved }">这是一个盒子</div>
  </div>
</template>

<script>
export default {
  name: 'slideView',
  data() {
    return {
      isMoved: false,
    }
  },
  methods: {
    toggleBox() {
      this.isMoved = !this.isMoved
    },
  },
}
</script>

<style lang="scss" scoped>
.box {
  width: 200px;
  height: 100px;
  background-color: #3498db;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 20px 0;
  border-radius: 5px;
  position: relative; /* 需要相对定位 */
  animation-duration: 0.5s; /* 动画时长 */
}

.slideRight {
  animation-name: slideRight;
  animation-fill-mode: forwards; /* 保持最终状态 */
}

.slideLeft {
  animation-name: slideLeft;
  animation-fill-mode: forwards; /* 保持最终状态 */
}

@keyframes slideRight {
  from {
    transform: translateX(0); /* 初始位置 */
  }
  to {
    transform: translateX(200px); /* 移动 200px */
  }
}

@keyframes slideLeft {
  from {
    transform: translateX(200px); /* 从右边开始 */
  }
  to {
    transform: translateX(0); /* 移动回原点 */
  }
}
</style>
